package com.daisuxia.web.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.daisuxia.back.dao.IBackConfigParamsDao;
import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.constant.Constant;
import com.daisuxia.risk.service.IOutOrdersService;
import com.daisuxia.risk.utils.ThreadPool;
import com.daisuxia.web.common.reslult.Status;
import com.daisuxia.web.dao.IBorrowOrderDao;
import com.daisuxia.web.dao.IBorrowOrderLoanDao;
import com.daisuxia.web.dao.IBorrowOrderLoanPersonDao;
import com.daisuxia.web.dao.IPaginationDao;
import com.daisuxia.web.dao.IRepaymentDao;
import com.daisuxia.web.dao.IUserBankDao;
import com.daisuxia.web.dao.IUserDao;
import com.daisuxia.web.dao.IUserLimitRecordDao;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.BorrowOrderLoan;
import com.daisuxia.web.pojo.BorrowOrderLoanPerson;
import com.daisuxia.web.pojo.OutOrders;
import com.daisuxia.web.pojo.Repayment;
import com.daisuxia.web.pojo.RiskCreditUser;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.pojo.UserCardInfo;
import com.daisuxia.web.pojo.UserLimitRecord;
import com.daisuxia.web.test.HttpRequestCMBDF;
import com.daisuxia.web.test.HttpRequestCMBHL;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.GenerateNo;
import com.daisuxia.web.util.PageConfig;
import com.daisuxia.web.util.SendSmsUtil;

/**
 * 
 * 
 * @ClassName: BorrowService.java
 * @Description: TODO
 * @author zhangjb
 * @version V1.0
 * @Date 2016年12月12日 下午7:22:00
 */
@Service
public class BorrowOrderService implements IBorrowOrderService {
	private static Logger logger = LoggerFactory.getLogger(IBorrowOrderService.class);

	@Autowired
	IBackConfigParamsDao backConfigParamsDao;

	@Autowired
	@Qualifier("userBankDaoImpl")
	private IUserBankDao userBankDao;

	@Autowired
	private IBorrowOrderDao borrowOrderDao;
	@Autowired
	private IPaginationDao paginationDao;

	@Autowired
	private IUserDao userDao;
	@Autowired
	private IUserLimitRecordDao userLimitRecordDao;

	@Autowired
	private IRepaymentDao repaymentDao;
	@Autowired
	private IInfoIndexService infoIndexService;
	@Autowired
	private IOutOrdersService outOrdersService;

	@Autowired
	private IRepaymentService repaymentService;
	@Autowired
	private IBorrowOrderLoanDao borrowOrderLoanDao;
	@Autowired
	private IBorrowOrderLoanPersonDao borrowOrderLoanPersonDao;
	@Autowired
	private SequenceManagerService sequenceManagerService;

	@Override
	public List<BorrowOrder> findAll(HashMap<String, Object> params) {
		// TODO Auto-generated method stub
		return borrowOrderDao.findParams(params);
	}

	@Override
	public BorrowOrder findOneBorrow(Integer id) {

		return borrowOrderDao.selectByPrimaryKey(id);

	}

	@Override
	public void deleteById(Integer id) {
		// TODO Auto-generated method stub

	}

	@Override
	public void insert(BorrowOrder borrowOrder) {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateById(BorrowOrder borrowOrder) {
		borrowOrderDao.updateByPrimaryKeySelective(borrowOrder);

	}

	@Override
	public PageConfig<BorrowOrder> findPage(HashMap<String, Object> params) {
		params.put(Constant.NAME_SPACE, "BorrowOrder");
		return paginationDao.findPage("findParams", "findParamsCount", params, "web");
	}

	public int findParamsCount(HashMap<String, Object> params) {
		return borrowOrderDao.findParamsCount(params);
	}

	@Override
	public Map<String, Object> saveLoan(Map<String, String> params, User user) {
		Map<String, Object> result = new HashMap<String, Object>();

		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("userId", user.getId()); //
		param.put("type", "2"); // 借记卡
		List<UserCardInfo> cardInfo = userBankDao.findUserCardByUserId(param);
		UserCardInfo info = new UserCardInfo();
		if (cardInfo != null && cardInfo.size() > 0) {
			info = cardInfo.get(0);
		} else {
			result.put("code", Status.FAILD.getName());
			result.put("msg", "请先绑定银行卡");
			return result;
		}
		List<BorrowOrder> boList = borrowOrderDao.findByUserId(Integer.valueOf(user.getId()));
		List<Integer> paying = new ArrayList<Integer>();
		paying.add(22);
		paying.add(25);
		for (BorrowOrder bo:boList){
			if(paying.contains(bo.getStatus())){
				result.put("code", Status.FAILD.getName());
				result.put("msg", "您当前有处理中的借款, 请不要重复提交");
				return result;
			}
		}
		// 获取滞纳金/借款服务费率走向，用户拆分服务费
		Map<String, String> intervalMap = SysCacheUtils.getConfigMap(BackConfigParams.SYS_FEE);
		Integer lateApr = Integer.valueOf(intervalMap.get("fee_lateapr"));
		Integer fee_company = Integer.valueOf(intervalMap.get("fee_company")); // 公司
		Integer fee_person = Integer.valueOf(intervalMap.get("fee_person")); // 个人
		// 查询银行信息
		Map<String, String> bankInfo = userBankDao.selectByPrimaryKey(info.getBank_id());
		Integer bank_iscmb = 2; // 是否是招商银行 ，默认：1：是，2：否
		if (bankInfo != null && "0308".equals(bankInfo.get("bankCode"))) {
			bank_iscmb = 1;
		}
		// 计算服务费率
		Integer money = Integer.parseInt(params.get("money")) * 100; // 借款金额
																		// ，单位：分
		Map<String, Integer> fee = this.calculateApr(money, Integer.parseInt(params.get("period")));
		Integer intoMoney = money - fee.get("loanApr");
		Date date = new Date();
		BorrowOrder bo = new BorrowOrder();
		bo.setUserId(Integer.parseInt(user.getId()));
		bo.setOutTradeNo(String.valueOf(sequenceManagerService.getNewId()));
		bo.setMoneyAmount(money);
		bo.setApr(fee.get("apr"));
		bo.setLoanInterests(fee.get("loanApr"));
		bo.setIntoMoney(intoMoney);
		bo.setLoanTerm(Integer.parseInt(params.get("period")));
		bo.setCreatedAt(date);
		bo.setUpdatedAt(date);
		bo.setOrderTime(date);
		bo.setLateFeeApr(lateApr);
		bo.setReceiveCardId(info.getBank_id());
		bo.setUserPhone(user.getUserPhone());
		bo.setRealname(user.getRealname());
//		bo.setBankNumber(bankInfo.get("bankNumber"));
		bo.setBankNumber(bankInfo.get("bankName"));
		
		bo.setCardNo(info.getCard_no());
		bo.setBankIscmb(bank_iscmb);
		bo.setYurref(GenerateNo.payRecordNo("A"));
		bo.setCustomerType(Integer.parseInt(user.getCustomerType()));
		bo.setIdNumber(user.getIdNumber());
		bo.setSerialNo(GenerateNo.generateShortUuid(10));
		borrowOrderDao.insertSelective(bo);

		// 计算保存到公司的服务费
		Integer loan_interests = (Integer) bo.getLoanInterests() * fee_company / 100;
		BorrowOrderLoan loan = new BorrowOrderLoan();
		loan.setUserId(Integer.parseInt(user.getId()));
		loan.setAssetOrderId(bo.getId());
		loan.setLoanInterests(loan_interests);
		// loan.setYurref(GenerateNo.payRecordNo("B"));
		loan.setCreatedAt(date);
		loan.setUpdatedAt(date);
		borrowOrderLoanDao.insertSelective(loan);
		// 计算保存到个人的服务费
		Integer interests_p = (Integer) bo.getLoanInterests() * fee_person / 100;
		BorrowOrderLoanPerson personLoan = new BorrowOrderLoanPerson();
		personLoan.setUserId(Integer.parseInt(user.getId()));
		personLoan.setAssetOrderId(bo.getId());
		personLoan.setLoanInterests(interests_p);
		// personLoan.setYurref(GenerateNo.payRecordNo("C"));
		personLoan.setCreatedAt(date);
		personLoan.setUpdatedAt(date);
		borrowOrderLoanPersonDao.insertSelective(personLoan);

		Integer amountAvailable = Integer.parseInt(user.getAmountAvailable());
		User upd = new User();
		upd.setAmountAvailable(String.valueOf(amountAvailable - money));
		upd.setId(user.getId());
		userDao.updateAmountAvailableByUserId(upd);

		Integer addAmount = 0;
		Map<String, BigDecimal> userLimit = userLimitRecordDao.countAddAmount(Integer.parseInt(user.getId()));
		if (userLimit.get("add_amount") != null) {
			addAmount = userLimit.get("add_amount").intValue();
		}
		RiskCreditUser risk = new RiskCreditUser();
		risk.setUserId(Integer.parseInt(user.getId()));
		risk.setAssetId(bo.getId());
		risk.setCardNum(user.getIdNumber());
		risk.setUserName(user.getRealname());
		risk.setAge(user.getUserAge());
		risk.setEducation(Integer.parseInt(StringUtils.isNotBlank(user.getEducation()) ? user.getEducation() : "7"));
		if ("男".equals(user.getUserSex())) {
			risk.setSex(1);
		} else if ("女".equals(user.getUserSex())) {
			risk.setSex(2);
		}
		risk.setUserPhone(user.getUserPhone());

		risk.setAmountAddsum(new BigDecimal(addAmount / 100.00));
		risk.setMoneyAmount(new BigDecimal(bo.getMoneyAmount() / 100.00));
		borrowOrderDao.insertRiskUser(risk);

		result.put("code", Status.SUCCESS.getName());
		result.put("msg", Status.SUCCESS.getValue());
		result.put("orderId", bo.getId());
		return result;
	}

	/**
	 * 计算服务费 money 用户借款额度 单位：分
	 * 
	 * @param period
	 * @param money
	 * @return
	 */
	public Map<String, Integer> calculateApr(Integer money, Integer period) {
		Map<String, Integer> result = new HashMap<String, Integer>();
		double apr = 0;
		Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.SYS_FEE);
		String periodTypes = keys.get("period_type_isopen");
		try {

			String periodTypesArr[] = periodTypes.split(";");
			for (String p : periodTypesArr) {
				String periods[] = p.split(":");
				if (period.toString().equals(periods[0])) {
					apr = Double.valueOf(periods[2]);
					break;
				}
			}
		} catch (Exception e) {
			logger.error("judge periodsTypeIsOpen error", e);
			// 服务费费率，单位：万分之
			if (7 == period) {
				apr = Constant.RATE_MIN;
			} else if (14 == period) {
				apr = Constant.RATE_MAX;
			}
		}
		Integer loanApr = 0; // 服务费
		loanApr = (int) (money * apr);
		result.put("loanApr", loanApr);
		result.put("apr", (int) (apr * 10000)); // 费率由百分比转换成万分比
		return result;
	}

	@Override
	public void authBorrowState(BorrowOrder borrowOrder) {

		BorrowOrder borrowOrderR = borrowOrderDao.selectByPrimaryKey(borrowOrder.getId());

		// ======================================以下状态需要第三方回调通知放款结果调用，见下方方法creditReCallBack=========================================
		if (borrowOrder.getStatus().intValue() == BorrowOrder.STATUS_HKZ.intValue()) {// 放款成功
			Date fkDate = new Date();
			borrowOrder.setLoanTime(fkDate);
			borrowOrder.setLoanEndTime(DateUtil.addDay(fkDate, borrowOrderR.getLoanTerm()));// 放款时间加上借款期限
			Repayment repayment = new Repayment();
			repayment.setUserId(borrowOrderR.getUserId());
			repayment.setAssetOrderId(borrowOrderR.getId());
			repayment.setRepaymentAmount(Long.valueOf(borrowOrderR.getMoneyAmount()));
			repayment.setLateFeeApr(borrowOrderR.getLateFeeApr());
			repayment.setRepaymentedAmount(0L);
			repayment.setRepaymentPrincipal(Long.valueOf(borrowOrderR.getIntoMoney()));
			repayment.setRepaymentInterest(Long.valueOf(borrowOrderR.getLoanInterests()));

			repayment.setRepaymentTime(DateUtil.addDay(fkDate, borrowOrderR.getLoanTerm()));// 放款时间加上借款期限
			repayment.setCreatedAt(fkDate);
			repayment.setUpdatedAt(fkDate);
			repayment.setStatus(borrowOrder.getStatus());
			repaymentDao.insert(repayment);

		}

		// ===============================================================================

		// borrowOrderService.updateById(borrowOrder);
		borrowOrderDao.updateByPrimaryKeySelective(borrowOrder);
		// 放款审核通过，需要完善判断，防止前端修改状态
		if (borrowOrder.getStatus().intValue() == BorrowOrder.STATUS_FKZ) {

			logger.info("调用第三方放款接口");
			// 调用第三方去放款

		}

	}

	@Override
	public void addUserLimit(User user) {
		// user=new User();
		// user.setId("28");
		logger.error("begin add userLimit userId:" + user.getId());
		Integer tgApr = 0;// 本次提额百分比，7天（sevenAmountaddFee%）、14天(fourteenAmountaddFee%)
		Integer tgJs = 0;// 提额计算提额金额的基数
		Integer tgMoneyType = 0;// 提额等级
		Integer addAmount = 0;// 本次提额金额( (tgJs * tgApr / 100))
		Date lastTeDate = null;// 上次提额时间
		Integer sucCount = 0;
		Integer sucAmount = 0;
		Integer normCount = 0;//?成功还款的记录总数
		Integer normAmount = 0;// 累计还款金额
		try {
			if (user != null) {

				Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.SYS_FEE);
				// 7天借款额度增加比例	--3
				Integer sevenAmountaddFee = Integer.parseInt(keys.get("seven_amountadd_fee"));
				// 14天借款额度增加比例	--5
				Integer fourteenAmountaddFee = Integer.parseInt(keys.get("fourteen_amountadd_fee"));
				// 系统最大额度			--1500
				Integer sysAmountMax = Integer.parseInt(keys.get("max_amount_sys"));
				HashMap<String, Object> params = new HashMap<String, Object>();

				params.put("userId", user.getId());
				params.put("statusList", Arrays.asList(BorrowOrder.STATUS_YHK));
				
				//查询出当前账户所有的还款成功的记录
				List<BorrowOrder> normOrders = borrowOrderDao.findParams(params);
				if (normOrders != null && normOrders.size() > 0) {
					// tgApr = 5(我们这里只做14天的，所以这里费率就是5)
					tgApr = normOrders.get(0).getLoanTerm() == 7 ? sevenAmountaddFee : fourteenAmountaddFee;// 2017-02-15
					// 拿到当前账户所有的借款金额
					for (BorrowOrder bor : normOrders) {
						normAmount += bor.getMoneyAmount();
					}

					normCount = normOrders.size();
				}
				if (!(normAmount < 100000)) {
					tgMoneyType = normAmount / 100000;// 获取本次提额等级

					params.clear();
					params.put("userId", user.getId());
					params.put("status", UserLimitRecord.STATUS_PASS_SUCC);
					List<UserLimitRecord> userlimits = userLimitRecordDao.findListBayParams(params);
					// 已经有过的提额等级
					ArrayList<Integer> hasTe = new ArrayList<Integer>();
					if (userlimits != null && userlimits.size() > 0) {
						lastTeDate = userlimits.get(0).getUpdatedAt();
						for (UserLimitRecord bor : userlimits) {
							hasTe.add(bor.getAddReasonType());
						}
					}
					// 历史提额等级中不包含本次提额等级
					if (!hasTe.contains(tgMoneyType) && tgApr > 0 && tgMoneyType > 0) {
						sucAmount = normAmount;
						sucCount = normCount;

						params.clear();
						params.put("userId", user.getId());
						params.put("statusList", Arrays.asList(BorrowOrder.STATUS_YQYHK));
						List<BorrowOrder> yqOrders = borrowOrderDao.findParams(params);
						if (yqOrders != null && yqOrders.size() > 0) {
							for (BorrowOrder bor : yqOrders) {
								sucAmount += bor.getMoneyAmount();
							}
							sucCount += yqOrders.size();
						}
						//tgJs = tgMoneyType * 100000;
						tgJs = 1 * 100000;
						addAmount = (tgJs * tgApr / 100);
						Integer oldAmountMax = Integer.parseInt(user.getAmountMax());
						Integer newAmountMax = oldAmountMax + addAmount;

						if (newAmountMax > sysAmountMax) {
							logger.error("addUserLimit  param old:" + newAmountMax + ",more then sysAmountMax:" + sysAmountMax
									+ ",change to sysAmountMax");
							newAmountMax = sysAmountMax;
						}
						if (newAmountMax > oldAmountMax) {
							Date nowDate = new Date();
							UserLimitRecord record = new UserLimitRecord();
							record.setUserId(Integer.parseInt(user.getId()));
							record.setCreateAt(nowDate);
							record.setUpdatedAt(nowDate);
							record.setAddAmount(addAmount);
							record.setAddReasonType(tgMoneyType);
							record.setLastApplyAt(lastTeDate);
							record.setStatus(UserLimitRecord.STATUS_PASS_SUCC);
							record.setOldAmountMax(oldAmountMax);
							record.setAuditUser("系统");
							record.setNewAmountMax(newAmountMax);
							record.setRemark("累计正常还款" + normAmount / 100 + "元,系统自动提额" + addAmount / 100 + "元");

							record.setRepaymentSuccCount(sucCount);
							record.setRepaymentSuccAmount(sucAmount);
							record.setRepaymentNormCount(normCount);
							record.setRepaymentNormAmount(normAmount);
							//record.setRealname(user.getRealname());
							//record.setUserPhone(user.getUserPhone());
							
							userLimitRecordDao.insertSelective(record);

							User newUser = new User();
							newUser.setId(user.getId());
							newUser.setAmountMax(String.valueOf(record.getNewAmountMax()));
							newUser.setAmountAvailable(String.valueOf(Integer.valueOf(user.getAmountAvailable()) + addAmount));
							newUser.setAmountAddsum(String.valueOf(Integer.valueOf(user.getAmountAddsum()) + addAmount));
							newUser.setUpdateTime(nowDate);
//							userDao.updateByPrimaryKeyUser(newUser);
							userDao.updateAmountByUserId(newUser);
							
							logger.error("addUserLimit sucess 提额成功！");
							// 更新个人信息缓存
							HashMap<String, Object> map = new HashMap<String, Object>();
							map.put("userId", user.getId());
							infoIndexService.changeUserAmount(map);

							final String userPhone = user.getUserPhone();
							final Integer normAmountT = normAmount / 100;
							final Integer addAmountT = addAmount / 100;
							ThreadPool.getInstance().run(new Runnable() {
								@Override
								public void run() {
									// 发送提额短信
									SendSmsUtil.sendSmsDiyCL(userPhone, "恭喜您已经正常还款累计" + normAmountT + "元，获得提额：" + addAmountT + "元，请继续保持良好的还款习惯！");
								}
							});

						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("addUserLimit error 计算提额错误！",e);
		}

	}

	@Override
	public void changeUserLimit(HashMap<String, Object> mapParam) {
		Integer newAmountMax = Integer.parseInt(String.valueOf(mapParam.get("newAmountMax")));
		// 系统最大额度
		Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.SYS_FEE);
		Integer sysAmountMax = Integer.parseInt(keys.get("max_amount_sys"));
		if (newAmountMax > sysAmountMax) {
			logger.error("changeUserLimit  param old:" + newAmountMax + ",more then sysAmountMax:" + sysAmountMax + ",change to sysAmountMax");
			newAmountMax = sysAmountMax;
		}

		logger.error("begin change userLimit userId:" + mapParam.get("userId"));
		UserLimitRecord record = new UserLimitRecord();
		record.setUserId(Integer.parseInt(String.valueOf(mapParam.get("userId"))));
		record.setNewAmountMax(newAmountMax);
		logger.error(mapParam.get("userId") + "  risk send amount " + newAmountMax);
		User user = userDao.searchByUserid(record.getUserId());
		logger.error(mapParam.get("userId") + " read db amount " + user.getAmountMax());

		Integer tgMoneyType = 0;// 提额等级0为风控提额
		Integer addAmount = 0;// 本次提额金额( (tgJs * tgApr / 100))

		try {
			if (user != null) {

				addAmount = record.getNewAmountMax() - Integer.parseInt(user.getAmountMax());
				if (addAmount != 0) {

					Date lastTeDate = null;// 上次提额时间
					HashMap<String, Object> params = new HashMap<String, Object>();
					params.clear();
					params.put("userId", user.getId());
					params.put("status", UserLimitRecord.STATUS_PASS_SUCC);
					List<UserLimitRecord> userlimits = userLimitRecordDao.findListBayParams(params);
					// 已经有过的提额等级
					ArrayList<Integer> hasTe = new ArrayList<Integer>();
					if (userlimits != null && userlimits.size() > 0) {
						lastTeDate = userlimits.get(0).getUpdatedAt();

					}

					Date nowDate = new Date();
					record = new UserLimitRecord();
					record.setUserId(Integer.parseInt(user.getId()));
					record.setCreateAt(nowDate);
					record.setUpdatedAt(nowDate);
					record.setAddAmount(addAmount);
					record.setAddReasonType(tgMoneyType);
					record.setLastApplyAt(lastTeDate);
					record.setStatus(UserLimitRecord.STATUS_PASS_SUCC);
					record.setOldAmountMax(Integer.parseInt(user.getAmountMax()));
					record.setAuditUser("风控");
					record.setNewAmountMax(Integer.parseInt(user.getAmountMax()) + addAmount);
					record.setRemark("风控运行,系统自动提额" + addAmount / 100 + "元");
					record.setRealname(user.getRealname());
					record.setUserPhone(user.getUserPhone());
					
					userLimitRecordDao.insertSelective(record);

					User newUser = new User();
					newUser.setId(user.getId());
					newUser.setAmountMax(String.valueOf(record.getNewAmountMax()));
					newUser.setAmountAvailable(String.valueOf(Integer.valueOf(user.getAmountAvailable()) + addAmount));
					newUser.setAmountAddsum(String.valueOf(Integer.valueOf(user.getAmountAddsum()) + addAmount));
					newUser.setUpdateTime(nowDate);
//					userDao.updateByPrimaryKeyUser(newUser);
					userDao.updateAmountByUserId(newUser);
					logger.error("changeUserLimit sucess 额度修改成功！");
					// 更新个人信息缓存
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("userId", user.getId());
					infoIndexService.changeUserAmount(map);
					final String userPhone = user.getUserPhone();
					final Integer amountMax = Integer.parseInt(newUser.getAmountMax()) / 100;
					if (amountMax > 0) {
						ThreadPool.getInstance().run(new Runnable() {

							@Override
							public void run() {

								// 发送提额短信
								SendSmsUtil.sendSmsDiyCL(userPhone, "通过风控运行，您的额度更改为：" + amountMax + "元，请保持良好的还款习惯！");
								// System.out.println("恭喜您已经正常还款累计" + normAmount
								// /
								// 100+
								// "元，获得提额："+addAmount/100+"元，请继续保持良好的还款习惯！");
							}
						});
					}
				}

			} else {

				logger.error("begin change userLimit user not  exsit:" + mapParam.get("userId"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("changeUserLimit error 额度修改错误！");
		}

	}

	@Override
	public PageConfig<UserLimitRecord> finduserLimitPage(HashMap<String, Object> params) {
		params.put(Constant.NAME_SPACE, "UserLimitRecord");
		return paginationDao.findPage("findListBayParams", "findParamsCount", params, "web");
	}

	@Override
	public BorrowOrder selectBorrowOrderUseId(Integer userId) {
		return borrowOrderDao.selectBorrowOrderUseId(userId);
	}

	/**
	 * 检查当前用户是否存在未还款完成的订单
	 * 
	 * @param userId
	 * @return 1：是；0：否
	 */
	public Integer checkBorrow(Integer userId) {
		Integer result = 0;
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("userId", userId);
		params.put("statusList", Arrays.asList(BorrowOrder.STATUS_DCS,
				// BorrowOrder.STATUS_JSJJ,
				BorrowOrder.STATUS_CSTG, BorrowOrder.STATUS_FSTG, BorrowOrder.STATUS_HKZ, BorrowOrder.STATUS_FKZ, BorrowOrder.STATUS_FKSB,
				BorrowOrder.STATUS_BFHK, BorrowOrder.STATUS_YYQ, BorrowOrder.STATUS_YHZ));
		List<BorrowOrder> normOrders = borrowOrderDao.findParams(params);
		if (normOrders != null && normOrders.size() > 0) {
			result = 1;
		}
		return result;
	}

	@Override
	public void updateRiskCreditUserById(com.daisuxia.risk.pojo.RiskCreditUser riskCreditUser) {

		borrowOrderDao.updateRiskCreditUserById(riskCreditUser);
	}

	@Override
	public List<BorrowOrder> findByUserId(Integer userId) {
		return borrowOrderDao.findByUserId(userId);
	}

	@Override
	public void requestPay(BorrowOrder borrowOrder) {

		try {

			List<BorrowOrder> bds = new ArrayList<BorrowOrder>();
			bds.add(borrowOrder);
			String requestParams = HttpRequestCMBHL.getRequestNTIBCOPRStr(bds);
			logger.info("requestParams NTQRYEBP_A_2 Loan  :" + requestParams);

			// 插入订单
			OutOrders orders = new OutOrders();
			orders.setUserId(String.valueOf(borrowOrder.getUserId()));
			orders.setOrderNo(GenerateNo.nextOrdId());
			orders.setOrderType(OutOrders.orderType_cmb);
			orders.setAssetOrderId(borrowOrder.getId());
			orders.setReqParams(requestParams);
			orders.setAddTime(new Date());
			orders.setAct("NTIBCOPR_A");
			orders.setStatus(OutOrders.STATUS_WAIT);
			outOrdersService.insert(orders);

			// 连接前置机，发送请求报文，获得返回报文
			String result = HttpRequestCMBHL.sendRequest(requestParams);
			logger.info("resutParams NTQRYEBP_A_2 Loan :" + result);
			// 更新订单
			OutOrders ordersNew = new OutOrders();
			ordersNew.setId(orders.getId());

			// ordersNew.setOrderNo(borrowOrder.getOutTradeNo());
			ordersNew.setReturnParams(result);
			ordersNew.setUpdateTime(new Date());
			ordersNew.setStatus(OutOrders.STATUS_SUC);
			outOrdersService.update(ordersNew);

			// 处理返回的结果
			ServiceResult serviceResult = HttpRequestCMBHL.processPayResult(result);
			logger.info("result NTQRYEBP_A_2 Loan  :" + serviceResult.getCode() + ">>" + serviceResult.getMsg());

			String paystatus = serviceResult.getCode();
			String payRemark = serviceResult.getMsg();
			// 更新借款表

			Date fkDate = new Date();
			BorrowOrder borrowOrderNew = new BorrowOrder();
			borrowOrderNew.setId(borrowOrder.getId());
			borrowOrderNew.setPaystatus(paystatus);
			borrowOrderNew.setPayRemark(payRemark);
			borrowOrderNew.setUpdatedAt(fkDate);
			// borrowOrderNew.setYurref(borrowOrder.getYurref());
			if (paystatus.equals(BorrowOrder.SUB_PAY_SUCC)) {
				borrowOrderNew.setLoanTime(fkDate);
				borrowOrderNew.setStatus(BorrowOrder.STATUS_HKZ);

				borrowOrder.setLoanTime(fkDate);
				borrowOrder.setLoanEndTime(DateUtil.addDay(fkDate, borrowOrder.getLoanTerm()));// 放款时间加上借款期限

				// 放款成功插入还款记录
				borrowOrder.setPaystatus(borrowOrderNew.getPaystatus());
				borrowOrder.setStatus(BorrowOrder.STATUS_HKZ);
				borrowOrder.setLoanTime(fkDate);
				borrowOrder.setLoanEndTime(borrowOrderNew.getLoanEndTime());// 放款时间加上借款期限

				repaymentService.insertByBorrorOrder(borrowOrder);

			}

			borrowOrderDao.updateByPrimaryKeySelective(borrowOrderNew);
		} catch (Exception e) {
			logger.error("requestPay NTQRYEBP_A_2 error......");
			e.printStackTrace();
		}
	}

	@Override
	public void requestPaysNotCmbUser(List<BorrowOrder> borrowOrders) {
		try {
			ServiceResult serviceResult = subPayNotCmb(borrowOrders, OutOrders.act_NTQRYEBP_A);
			String paystatus = serviceResult.getCode();
			String payRemark = serviceResult.getMsg();
			// 更新借款表
			Date fkDate = new Date();
			for (BorrowOrder bo : borrowOrders) {
				BorrowOrder borrowOrderNew = new BorrowOrder();
				borrowOrderNew.setId(bo.getId());
				borrowOrderNew.setPaystatus(paystatus);
				borrowOrderNew.setPayRemark(payRemark);
				borrowOrderNew.setUpdatedAt(fkDate);
				// borrowOrderNew.setYurref(borrowOrder.getYurref());
				if (paystatus.equals(BorrowOrder.SUB_PAY_SUCC)) {// 如果等于成功，更新还款表
					borrowOrderNew.setLoanTime(fkDate);
					borrowOrderNew.setStatus(BorrowOrder.STATUS_HKZ);
					bo.setLoanTime(fkDate);
					bo.setLoanEndTime(DateUtil.addDay(fkDate, bo.getLoanTerm()));// 放款时间加上借款期限
					// 放款成功插入还款记录
					bo.setPaystatus(borrowOrderNew.getPaystatus());
					bo.setStatus(BorrowOrder.STATUS_HKZ);
					bo.setLoanTime(fkDate);
					bo.setLoanEndTime(borrowOrderNew.getLoanEndTime());// 放款时间加上借款期限
					repaymentService.insertByBorrorOrder(bo);
				}
				borrowOrderDao.updateByPrimaryKeySelective(borrowOrderNew);

			}

		} catch (Exception e) {
			logger.error("requestPay NTQRYEBP_A_2 Loan  error......");
			e.printStackTrace();
		}

	}

	@Override
	public void requestPaysCmbUser(List<BorrowOrder> borrowOrders) {
		try {

			ServiceResult serviceResult = subPayCmb(borrowOrders, OutOrders.act_AgentRequest_A);
			String paystatus = serviceResult.getCode();
			String payRemark = serviceResult.getMsg();
			// 更新借款表
			Date fkDate = new Date();

			for (BorrowOrder bo : borrowOrders) {
				BorrowOrder borrowOrderNew = new BorrowOrder();
				borrowOrderNew.setId(bo.getId());
				borrowOrderNew.setPaystatus(paystatus);
				borrowOrderNew.setPayRemark(payRemark);
				borrowOrderNew.setUpdatedAt(fkDate);
				// borrowOrderNew.setYurref(borrowOrder.getYurref());
				// if (paystatus.equals(BorrowOrder.SUB_PAY_SUCC)) {//
				// 如果等于成功，更新还款表
				// borrowOrderNew.setLoanTime(fkDate);
				// borrowOrderNew.setStatus(BorrowOrder.STATUS_HKZ);
				// bo.setLoanTime(fkDate);
				// bo.setLoanEndTime(DateUtil.addDay(fkDate,
				// bo.getLoanTerm()));// 放款时间加上借款期限
				// // 放款成功插入还款记录
				// bo.setPaystatus(borrowOrderNew.getPaystatus());
				// bo.setStatus(BorrowOrder.STATUS_HKZ);
				// bo.setLoanTime(fkDate);
				// bo.setLoanEndTime(borrowOrderNew.getLoanEndTime());//
				// 放款时间加上借款期限
				// repaymentService.insertByBorrorOrder(bo);
				// }
				borrowOrderDao.updateByPrimaryKeySelective(borrowOrderNew);
			}

		} catch (Exception e) {
			logger.error("requestPay   Loan  error......" + OutOrders.act_AgentRequest_A);
			e.printStackTrace();
		}

	}

	@Override
	public ServiceResult subPayNotCmb(List<BorrowOrder> borrowOrders, String subType) {
		ServiceResult serviceResult = new ServiceResult(BorrowOrder.SUB_ERROR, "未知异常，请稍后重试！");
		try {

			String requestParams = HttpRequestCMBHL.getRequestNTIBCOPRStr(borrowOrders);
			logger.info("requestParams  Loan  :" + subType + requestParams);
			// 插入订单
			OutOrders orders = new OutOrders();
			orders.setOrderNo(GenerateNo.nextOrdId());
			orders.setOrderType(OutOrders.orderType_cmb);
			orders.setReqParams(requestParams);
			orders.setAddTime(new Date());
			orders.setAct(subType);
			orders.setStatus(OutOrders.STATUS_WAIT);
			outOrdersService.insert(orders);
			// 连接前置机，发送请求报文，获得返回报文
			String result = HttpRequestCMBHL.sendRequest(requestParams);

			logger.info("resutParams  Loan  :" + subType + result);
			// 更新订单
			OutOrders ordersNew = new OutOrders();
			ordersNew.setId(orders.getId());

			// ordersNew.setOrderNo(borrowOrder.getOutTradeNo());
			ordersNew.setReturnParams(result);
			ordersNew.setUpdateTime(new Date());
			ordersNew.setStatus(OutOrders.STATUS_SUC);
			outOrdersService.update(ordersNew);

			// 处理返回的结果
			serviceResult = HttpRequestCMBHL.processPayResult(result);
			logger.info("result Loan Loan   " + subType + serviceResult.getCode() + ">>" + serviceResult.getMsg());

		} catch (Exception e) {
			logger.error("requestPay   Loan  error......" + subType);
			e.printStackTrace();
		}
		return serviceResult;
	}

	@Override
	public ServiceResult subPayCmb(List<BorrowOrder> borrowOrders, String subType) {
		ServiceResult serviceResult = new ServiceResult(BorrowOrder.SUB_ERROR, "未知异常，请稍后重试！");
		try {

			String requestParams = HttpRequestCMBDF.getRequestNTIBCOPRStr(borrowOrders);
			logger.info("requestParams  Loan  :" + subType + requestParams);
			// 插入订单
			OutOrders orders = new OutOrders();
			orders.setOrderNo(GenerateNo.nextOrdId());
			orders.setOrderType(OutOrders.orderType_cmb);
			orders.setReqParams(requestParams);
			orders.setAddTime(new Date());
			orders.setAct(subType);
			orders.setStatus(OutOrders.STATUS_WAIT);
			outOrdersService.insert(orders);
			// 连接前置机，发送请求报文，获得返回报文
			String result = HttpRequestCMBDF.sendRequest(requestParams);
			logger.info("requestParams  Loan  :" + subType + result);
			// 更新订单
			OutOrders ordersNew = new OutOrders();
			ordersNew.setId(orders.getId());

			// ordersNew.setOrderNo(borrowOrder.getOutTradeNo());
			ordersNew.setReturnParams(result);
			ordersNew.setUpdateTime(new Date());
			ordersNew.setStatus(OutOrders.STATUS_SUC);
			outOrdersService.update(ordersNew);

			// 处理返回的结果
			serviceResult = HttpRequestCMBDF.processPayResult(result);
			logger.info("requestParams  Loan  :" + subType + serviceResult.getCode() + ">>" + serviceResult.getMsg());

		} catch (Exception e) {
			logger.error("requestPay   Loan  error......" + subType);
			e.printStackTrace();
		}
		return serviceResult;
	}

	@Override
	public Map<String, String> findAuditFailureOrderByUserId(String userId) {
		Map<String, String> result = new HashMap<String, String>();
		Integer code = 0;
		String msg = "";
		int nextLoanDay = 0;// 剩余可借款天数
		Integer interval_day = 0; // 申请失败距当前时间的间隔天数

		Map<String, String> intervalMap = SysCacheUtils.getConfigMap(BackConfigParams.INTERVAL);
		int interval = Integer.valueOf(intervalMap.get("INTERVAL_BORROW_AGAIN"));
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("userId", userId);
		params.put("statusList", Arrays.asList(BorrowOrder.STATUS_CSBH, BorrowOrder.STATUS_FSBH, BorrowOrder.STATUS_FKBH));
		BorrowOrder bo = borrowOrderDao.findAuditFailureOrderByUserId(params);
		if (bo != null) {
			Date date = new Date();
			Date smDate = new Date();
			try {
				if (bo.getVerifyLoanTime() != null) {
					smDate = bo.getVerifyLoanTime();
				} else if (bo.getVerifyReviewTime() != null) {
					smDate = bo.getVerifyReviewTime();
				} else if (bo.getVerifyTrialTime() != null) {
					smDate = bo.getVerifyTrialTime();
				}
				interval_day = DateUtil.daysBetween(smDate, date);
				code = interval_day < interval ? -1 : 0;

			} catch (ParseException e) {
				code = -1;
			}
			if (code == -1) {
				msg = "距离上次审核失败不足" + interval + "天，请" + (interval - interval_day) + "天后重新申请。";
				nextLoanDay = (interval - interval_day);
				result.put("canLoan", new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.addDay(smDate, interval - 1)));
			}
		}
		result.put("code", code + "");
		result.put("msg", msg);
		result.put("nextLoanDay", String.valueOf(nextLoanDay));
		return result;
	}
	
	@Override
	public BorrowOrder selectBorrowOrderNowUseId(Integer userId) {
		return borrowOrderDao.selectBorrowOrderNowUseId(userId);
	}

	@Override
	public BorrowOrder findOneBorrowByOutTradeNo(String outTradeNo) {
		return borrowOrderDao.selectByOutTradeNo(outTradeNo);
	}

}
